﻿/************************************************************************

  Extended Silverlight Toolkit – SAMPLE CODE

  Copyright (C) 2010-2012 Xceed Software Inc.

  This program is provided to you under the terms of the Microsoft Public
  License (Ms-PL) as published at http://extendedsilverlight.codeplex.com/license

  Please purchase a commercial version of this toolkit if you are using
  it in a commercial product. The commercial versions support the project,
  and also include more features for each control, priority support,
  source code, updates, removed watermark, and a proprietary license.

  Visit http://xceed.com and follow @datagrid on Twitter.

  **********************************************************************/

using System.Text.RegularExpressions;
using System.Windows.Data;

namespace Xceed.Utils.Silverlight.ListBox.Samples
{
  public class TaggedTextToTextConverter : IValueConverter
  {
    public object Convert( object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture )
    {
      string text = value.ToString();
      string result = string.Empty;

      Match match = TagRegex.Match( text );

      // If no tag was found
      if( !match.Success )
      {
        return text;
      }

      int index = match.Index;

      // Add the text before the first match to the para.
      result += text.Substring( 0, index );

      while( match.Success )
      {
        // match.Value and match.Groups[ 0 ] both represent the while match.
        // match.Groups[ 1 ] represents the type of tag (e.g., "a", "i")
        // match.Groups[ 2 ] represents the value of the tag (e.g., Rod Stewart)
        result += match.Groups[ 2 ].Value;
        index = match.Index + match.Length;
        match = match.NextMatch();

        // Add the text between the 2 successful matches only if the next match was successful.
        if( match.Success )
          result += text.Substring( index, match.Index - index );
      }

      // If there are no more matches, simply add the remainder or the text to the para.
      result += text.Substring( index );

      return result;
    }

    public object ConvertBack( object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture )
    {
      return value.ToString();
    }

    private static Regex TagRegex = new Regex( @"<([A-Z][A-Z0-9]*)\b[^>]*>(.*?)</\1>", RegexOptions.IgnoreCase );
  }
}
